package middleware

import (
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"sweeter.star/go-demo/common"
	"sweeter.star/go-demo/model"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Authorization")

		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
			c.Abort()
			return
		}
		tokenString = tokenString[7:]

		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "Token 无效"})
			c.Abort()
			return
		}

		// 验证通过后，获取用户信息
		uid := claims.UserId
		db := common.GetDB()

		var user model.User
		db.First(&user, uid)

		// 判断用户存在
		if user.ID == 0 {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "权限不足"})
			c.Abort()
			return
		}

		// 将用户写入上下文
		c.Set("user", user)
		c.Next()
	}
}